package com.soc.auth.security;

import cn.hutool.json.JSONUtil;
import com.soc.auth.constants.RedisConstants;
import com.soc.auth.domain.dto.RedisUser;
import com.soc.auth.domain.entity.User;
import com.soc.auth.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 登录成功后调用该方法
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        User user = securityUser.getUser();
        user.setPassword("");
        String userId = user.getId();

        List<String> roles = securityUser.getAuthorities().stream()
                .map((Function<GrantedAuthority, String>) GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        RedisUser redisUser = new RedisUser(user, roles);

        // 将用户信息存到 redis 中
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_USER_KEY + userId, redisUser, JwtUtil.JWT_REFRESH_TTL, TimeUnit.SECONDS);

        //生成accessToken
        String accessToken = JwtUtil.createJWT(userId, 500 * 60 * 60 * 1000 * 2L);
        //生成refresh_token
        String refreshToken = JwtUtil.createJWT(userId,JwtUtil.JWT_REFRESH_TTL);

        //把token和refreshToken封装 返回
        //Map<String,String> map = new HashMap<>();
        //map.put("token",accessToken);
        //map.put("refreshToken", refreshToken);

        //ResponseUtil.response(response, ResponseStatusEnum.OK, accessToken);

        log.info("用户：{} 登录成功！", securityUser.getUsername());

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "操作成功");
        res.put("token", accessToken);
        String resStr = JSONUtil.toJsonStr(res);
        response.setContentType("application/json;charset=utf-8");
        assert resStr != null;
        response.getWriter().write(resStr);
    }

}
